package com.zjj.distributed.zk.curator.watcher;

import com.zjj.distributed.zk.client.BaseOperations;
import com.zjj.distributed.zk.curator.CuratorBaseOperations;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.junit.Test;

/**
 * @author zhanglei.zjj
 * @description 使用 watcher 机制， 为一次性监听
 * @date 2023/6/20 21:08
 */
@Slf4j
public class CuratorWatcherTest extends CuratorBaseOperations {

    // 使用 watcher 机制， 为一次性监听
    @Test
    public void testWatcher() throws Exception {
        String path = "/test";
        createIfNeed(path, "test");
        byte[] bytes = curatorFramework.getData().usingWatcher(new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == Event.EventType.NodeDataChanged) {
                    log.info("node {} data changed!", event.getPath());
                }
            }
        }).forPath(path);

        log.info(" original data: {}", new String(bytes));
        log.info("start to change data.");
        curatorFramework.setData().forPath(path, "test".getBytes());
        log.info("start to change data again! ");
        curatorFramework.setData().forPath(path, "test".getBytes());

        Thread.sleep(Integer.MAX_VALUE);
    }
}
